<template>
    <label :class="['pr avt-b flex-center',value?'avt-b-b':'']">
        <i class="el-icon-error p-a f-20" v-if="value" @click.stop.prevent="clear"></i>
        <img v-if="value" class="avt" :src="value" alt="">
        <!-- 头像上传 -->
        <span v-else>
            上传头像
        </span>
        <input @change="handleUserInfo($event)" type="file" class="pos-so" />
      
    </label>
</template>

<script>
import { baseURL } from '@/plugins/config'
import { post_upload_imgs_common } from '@/api/blog/index.js'
export default {
    props: {
        value: {
            type: String,
            default: '',
        },
    },
    data() {
        return {}
    },
    methods: {
        async handleUserInfo(e) {
            try {
                let file = e.target.files[0]
                if (
                    file &&
                    ['image/png', 'image/jpg', 'image/jpeg'].includes(file.type.toLowerCase())
                ) {
                    const formData = new FormData()
                    formData.append('file', file)

                    const params = {
                        type: 'bn',
                    }
                    const res = await post_upload_imgs_common({
                        data: formData,
                        params,
                    })
                    let { netdisk_url } = res?.data || {}
                    if (!netdisk_url) {
                        this.$message.warning('上传图片失败')
                        return
                    }
                    this.$emit('input', `${baseURL}${netdisk_url}`)
                } else {
                    this.$message.warning('只支持jpg与png格式的图片')
                    return
                }

                e.target.value = ''
            } catch (err) {
                this.Toast(err)
            }
        },
        clear() {
            this.$emit('input', '')
        },
    },
}
</script>

<style lang="scss" scoped>
.pos-so {
    width: 0;
    height: 0;
    opacity: 0;
    position: absolute;
}
.el-icon-error{
    display: none;
    top: 2px;
    right: 2px;
}
.avt-b{
    width: 98px;
    height: 114px;
    border: 1px solid #e6e6e6;
   &:hover{
    .el-icon-error{
        display: block;   
    }
   }
}
.avt-b-b{
    border:none
}
.avt{
    width:100%;
    height:100%;
    object-fit: cover;
}
</style>
